<template>
  <div class="system-config">
    <div class="page-header">
      <h1>系统配置</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增配置
        </el-button>
        <el-button @click="exportConfigs">
          <el-icon><Download /></el-icon>
          导出配置
        </el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" class="config-tabs">
      <!-- 系统配置 -->
      <el-tab-pane label="系统配置" name="configs">
        <div class="config-container">
          <div class="config-header">
            <el-input
              v-model="searchText"
              placeholder="搜索配置项"
              style="width: 300px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="filterCategory" placeholder="选择分类" clearable style="width: 200px; margin-left: 10px">
              <el-option
                v-for="category in categories"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
            <el-switch
              v-model="showPublicOnly"
              active-text="仅显示公开配置"
              inactive-text="显示所有配置"
              style="margin-left: 20px"
            />
          </div>

          <div class="config-categories">
            <div v-for="category in filteredCategories" :key="category" class="category-section">
              <div class="category-header">
                <h3>{{ category }}</h3>
                <el-button size="small" @click="batchEdit(category)">批量编辑</el-button>
              </div>
              
              <el-table :data="getConfigsByCategory(category)" stripe>
                <el-table-column prop="config_key" label="配置键" width="200" />
                <el-table-column prop="config_value" label="配置值" min-width="200">
                  <template #default="{ row }">
                    <div v-if="row.editing" class="inline-edit">
                      <el-input
                        v-if="row.config_type === 'string'"
                        v-model="row.editValue"
                        size="small"
                      />
                      <el-input-number
                        v-else-if="row.config_type === 'number'"
                        v-model="row.editValue"
                        size="small"
                        style="width: 100%"
                      />
                      <el-switch
                        v-else-if="row.config_type === 'boolean'"
                        v-model="row.editValue"
                        size="small"
                      />
                      <el-input
                        v-else
                        v-model="row.editValue"
                        type="textarea"
                        :rows="2"
                        size="small"
                      />
                    </div>
                    <div v-else class="config-value">
                      <span v-if="row.config_type === 'boolean'">
                        <el-tag :type="(row.config_value === 'true' || row.config_value === true) ? 'success' : 'danger'">
                          {{ (row.config_value === 'true' || row.config_value === true) ? '是' : '否' }}
                        </el-tag>
                      </span>
                      <span v-else-if="row.config_type === 'json'" class="json-value">
                        {{ formatJsonValue(row.config_value) }}
                      </span>
                      <span v-else>{{ row.config_value }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="config_type" label="类型" width="100">
                  <template #default="{ row }">
                    <el-tag size="small" :type="getTypeColor(row.config_type)">
                      {{ row.config_type }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip />
                <el-table-column prop="is_public" label="公开" width="80">
                  <template #default="{ row }">
                    <el-icon v-if="row.is_public" color="#67C23A"><Check /></el-icon>
                    <el-icon v-else color="#F56C6C"><Close /></el-icon>
                  </template>
                </el-table-column>
                <el-table-column prop="is_editable" label="可编辑" width="80">
                  <template #default="{ row }">
                    <el-icon v-if="row.is_editable" color="#67C23A"><Check /></el-icon>
                    <el-icon v-else color="#F56C6C"><Close /></el-icon>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="{ row }">
                    <div v-if="row.editing" class="edit-actions">
                      <el-button size="small" type="primary" @click="saveConfig(row)">保存</el-button>
                      <el-button size="small" @click="cancelEdit(row)">取消</el-button>
                    </div>
                    <div v-else class="normal-actions">
                      <el-button size="small" @click="editConfig(row)" :disabled="!row.is_editable">编辑</el-button>
                      <el-button size="small" @click="viewConfig(row)">详情</el-button>
                      <el-button size="small" type="danger" @click="deleteConfig(row)">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 系统字典 -->
      <el-tab-pane label="系统字典" name="dictionaries">
        <div class="dictionary-container">
          <div class="dictionary-header">
            <el-select v-model="selectedDictType" placeholder="选择字典类型" style="width: 200px">
              <el-option
                v-for="type in dictTypes"
                :key="typeof type === 'object' ? type.dict_type : type"
                :label="typeof type === 'object' ? `${type.dict_type} (${type.count})` : (type || '未知类型')"
                :value="typeof type === 'object' ? type.dict_type : type"
              />
            </el-select>
            <el-button type="primary" @click="loadDictionaries" :disabled="!selectedDictType">
              查看字典
            </el-button>
            <el-button @click="showCreateDictDialog = true">
              <el-icon><Plus /></el-icon>
              新增字典项
            </el-button>
          </div>

          <div v-if="selectedDictType" class="dictionary-tree">
            <el-tree
              :data="dictionaryTreeData"
              :props="dictTreeProps"
              node-key="id"
              :expand-on-click-node="false"
              :render-content="renderDictNode"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建/编辑配置对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingConfig ? '编辑配置' : '新增配置'"
      width="600px"
    >
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="120px">
        <el-form-item label="配置键" prop="config_key">
          <el-input v-model="configForm.config_key" :disabled="!!editingConfig" />
        </el-form-item>
        <el-form-item label="配置值" prop="config_value">
          <el-input
            v-if="configForm.config_type === 'string'"
            v-model="configForm.config_value"
          />
          <el-input-number
            v-else-if="configForm.config_type === 'number'"
            v-model="configForm.config_value"
            style="width: 100%"
          />
          <el-switch
            v-else-if="configForm.config_type === 'boolean'"
            v-model="configForm.config_value"
          />
          <el-input
            v-else
            v-model="configForm.config_value"
            type="textarea"
            :rows="4"
            placeholder="请输入JSON格式的配置值"
          />
        </el-form-item>
        <el-form-item label="配置类型" prop="config_type">
          <el-select v-model="configForm.config_type" style="width: 100%">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="JSON" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="configForm.category" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="configForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="公开配置">
          <el-switch v-model="configForm.is_public" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="允许编辑">
          <el-switch v-model="configForm.is_editable" active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfigForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 创建字典项对话框 -->
    <el-dialog v-model="showCreateDictDialog" title="新增字典项" width="500px">
      <el-form :model="dictForm" :rules="dictRules" ref="dictFormRef" label-width="100px">
        <el-form-item label="字典类型" prop="dict_type">
          <el-input v-model="dictForm.dict_type" />
        </el-form-item>
        <el-form-item label="字典键" prop="dict_key">
          <el-input v-model="dictForm.dict_key" />
        </el-form-item>
        <el-form-item label="字典值" prop="dict_value">
          <el-input v-model="dictForm.dict_value" />
        </el-form-item>
        <el-form-item label="显示标签" prop="dict_label">
          <el-input v-model="dictForm.dict_label" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="dictForm.sort_order" style="width: 100%" />
        </el-form-item>
        <el-form-item label="父级">
          <el-select v-model="dictForm.parent_id" placeholder="选择父级（可选）" clearable style="width: 100%">
            <el-option
              v-for="dict in flatDictionaries"
              :key="dict.id"
              :label="Array.isArray(dict.dict_label) ? dict.dict_label.join(', ') : (dict.dict_label || '未命名')"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dictForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="dictForm.is_active" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDictDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDictionary">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量编辑对话框 -->
    <el-dialog v-model="showBatchEditDialog" title="批量编辑配置" width="800px">
      <div class="batch-edit-container">
        <h4>{{ batchEditCategory }} 分类配置</h4>
        <el-table :data="batchEditConfigs" stripe>
          <el-table-column prop="config_key" label="配置键" width="200" />
          <el-table-column prop="config_value" label="当前值" width="200" />
          <el-table-column label="新值" width="200">
            <template #default="{ row }">
              <el-input v-model="row.newValue" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showBatchEditDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBatchEdit">批量保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { ElMessage, ElMessageBox, ElButton, ElTag } from 'element-plus'
import { Plus, Search, Download, Check, Close, Edit, Delete } from '@element-plus/icons-vue'
import {
  systemConfigApi,
  type SystemConfig,
  type SystemDictionary
} from '@/api'
import { detectExtensionConflict, showNetworkTroubleshooting } from '@/utils/networkUtils'

// 响应式数据
const activeTab = ref('configs')
const configs = ref<SystemConfig[]>([])
const searchText = ref('')
const filterCategory = ref('')
const showPublicOnly = ref(false)
const categories = ref<string[]>([])
const showCreateDialog = ref(false)
const editingConfig = ref<SystemConfig | null>(null)

// 字典相关
const dictionaries = ref<SystemDictionary[]>([])
const selectedDictType = ref('')
const dictTypes = ref<string[]>([])
const dictionaryTreeData = ref<SystemDictionary[]>([])
const showCreateDictDialog = ref(false)
const flatDictionaries = ref<SystemDictionary[]>([])

// 批量编辑
const showBatchEditDialog = ref(false)
const batchEditCategory = ref('')
const batchEditConfigs = ref<any[]>([])

// 表单数据
const configForm = reactive({
  config_key: '',
  config_value: '',
  config_type: 'string',
  category: '',
  description: '',
  is_public: true,
  is_editable: true
})

const dictForm = reactive({
  dict_type: '',
  dict_key: '',
  dict_value: '',
  dict_label: '',
  sort_order: 0,
  parent_id: null,
  description: '',
  is_active: true
})

// 表单验证规则
const configRules = {
  config_key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
  config_value: [{ required: true, message: '请输入配置值', trigger: 'blur' }],
  config_type: [{ required: true, message: '请选择配置类型', trigger: 'change' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }]
}

const dictRules = {
  dict_type: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
  dict_key: [{ required: true, message: '请输入字典键', trigger: 'blur' }],
  dict_value: [{ required: true, message: '请输入字典值', trigger: 'blur' }],
  dict_label: [{ required: true, message: '请输入显示标签', trigger: 'blur' }]
}

// 树形组件属性
const dictTreeProps = {
  children: 'children',
  label: 'dict_label'
}

// 计算属性
const filteredCategories = computed(() => {
  let categoryList = categories.value
  
  if (filterCategory.value) {
    categoryList = categoryList.filter(cat => cat === filterCategory.value)
  }
  
  return categoryList
})

// 方法
const loadConfigs = async (retryCount = 0) => {
  try {
    const response = await systemConfigApi.getSystemConfigs()
    // 修复：API返回的是{configs: [...], total: number}格式，需要访问configs属性
    const configsData = response.data.configs || response.data
    configs.value = configsData.map(config => ({
      ...config,
      editing: false,
      editValue: config.config_value,
      originalValue: config.config_value
    }))
    
    // 提取分类列表
    const categorySet = new Set(configs.value.map(c => c.category))
    categories.value = Array.from(categorySet)
  } catch (error: any) {
    console.error('加载配置失败:', error)
    
    // 检查是否是网络连接问题或浏览器扩展冲突
    if (detectExtensionConflict(error) || 
        error.code === 'NETWORK_ERROR' || 
        error.message?.includes('Network Error')) {
      
      if (retryCount < 2) {
        ElMessage.warning(`网络连接异常，正在重试... (${retryCount + 1}/3)`)
        setTimeout(() => loadConfigs(retryCount + 1), 1000 * (retryCount + 1))
        return
      } else {
        // 显示详细的网络问题排查建议
        const troubleshooting = showNetworkTroubleshooting()
        console.log(troubleshooting)
        ElMessage({
          message: '网络连接失败，请查看控制台获取详细的问题排查建议',
          type: 'error',
          duration: 8000,
          showClose: true
        })
      }
    } else if (error.response?.status === 401) {
      ElMessage.error('认证失败，请重新登录')
    } else if (error.response?.status >= 500) {
      ElMessage.error('服务器错误，请稍后重试')
    } else {
      ElMessage.error(`加载配置失败: ${error.message || '未知错误'}`)
    }
  }
}

const getConfigsByCategory = (category: string) => {
  let categoryConfigs = configs.value.filter(c => c.category === category)
  
  if (searchText.value) {
    categoryConfigs = categoryConfigs.filter(c => 
      c.config_key.toLowerCase().includes(searchText.value.toLowerCase()) ||
      (c.description && c.description.toLowerCase().includes(searchText.value.toLowerCase()))
    )
  }
  
  if (showPublicOnly.value) {
    categoryConfigs = categoryConfigs.filter(c => c.is_public)
  }
  
  return categoryConfigs
}

const getTypeColor = (type: string) => {
  const colors = {
    string: 'info',
    number: 'success',
    boolean: 'warning',
    json: 'info'
  }
  return colors[type] || 'info'
}

const formatJsonValue = (value: string) => {
  try {
    const parsed = JSON.parse(value)
    return JSON.stringify(parsed, null, 2).substring(0, 100) + '...'
  } catch {
    return value
  }
}

const editConfig = (config: any) => {
  config.editing = true
  config.editValue = config.config_value
}

const cancelEdit = (config: any) => {
  config.editing = false
  config.editValue = config.originalValue
}

const saveConfig = async (config: any) => {
  try {
    await systemConfigApi.updateSystemConfig(config.id, {
      config_value: config.editValue
    })
    
    config.config_value = config.editValue
    config.originalValue = config.editValue
    config.editing = false
    
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const viewConfig = (config: SystemConfig) => {
  editingConfig.value = config
  Object.assign(configForm, config)
  showCreateDialog.value = true
}

const deleteConfig = async (config: SystemConfig) => {
  try {
    await ElMessageBox.confirm('确定要删除这个配置吗？', '确认删除', {
      type: 'warning'
    })
    
    await systemConfigApi.deleteSystemConfig(config.id)
    ElMessage.success('删除成功')
    loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const saveConfigForm = async () => {
  try {
    if (editingConfig.value) {
      await systemConfigApi.updateSystemConfig(editingConfig.value.id, configForm)
      ElMessage.success('更新成功')
    } else {
      await systemConfigApi.createSystemConfig(configForm)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    editingConfig.value = null
    resetConfigForm()
    loadConfigs()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const resetConfigForm = () => {
  Object.assign(configForm, {
    config_key: '',
    config_value: '',
    config_type: 'string',
    category: '',
    description: '',
    is_public: true,
    is_editable: true
  })
}

const batchEdit = (category: string) => {
  batchEditCategory.value = category
  batchEditConfigs.value = getConfigsByCategory(category).map(config => ({
    ...config,
    newValue: config.config_value
  }))
  showBatchEditDialog.value = true
}

const saveBatchEdit = async () => {
  try {
    const updates = batchEditConfigs.value
      .filter(config => config.newValue !== config.config_value)
      .map(config => ({
        id: config.id,
        config_value: config.newValue
      }))
    
    if (updates.length === 0) {
      ElMessage.warning('没有需要更新的配置')
      return
    }
    
    await systemConfigApi.batchUpdateSystemConfigs(updates)
    ElMessage.success(`成功更新 ${updates.length} 个配置`)
    
    showBatchEditDialog.value = false
    loadConfigs()
  } catch (error) {
    ElMessage.error('批量保存失败')
  }
}

const exportConfigs = async () => {
  try {
    // 这里应该实现配置导出功能
    ElMessage.info('导出功能开发中')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 字典相关方法
const loadDictTypes = async (retryCount = 0) => {
  try {
    const response = await systemConfigApi.getDictionaryTypes()
    // 修复：API返回的是{types: [...]}格式，需要访问types属性
    const typesData = response.data.types || response.data
    dictTypes.value = typesData
  } catch (error: any) {
    console.error('加载字典类型失败:', error)
    
    if (detectExtensionConflict(error) || 
         error.code === 'NETWORK_ERROR' || 
         error.message?.includes('Network Error')) {
       
       if (retryCount < 2) {
         ElMessage.warning(`加载字典类型失败，正在重试... (${retryCount + 1}/3)`)
         setTimeout(() => loadDictTypes(retryCount + 1), 1000 * (retryCount + 1))
         return
       } else {
         const troubleshooting = showNetworkTroubleshooting()
         console.log(troubleshooting)
         ElMessage({
           message: '网络连接失败，请查看控制台获取详细的问题排查建议',
           type: 'error',
           duration: 8000,
           showClose: true
         })
       }
    } else {
      ElMessage.error(`加载字典类型失败: ${error.message || '未知错误'}`)
    }
  }
}

const loadDictionaries = async (retryCount = 0) => {
  try {
    const response = await systemConfigApi.getSystemDictionaryTree(selectedDictType.value)
    // 修复：API可能返回包装格式，需要处理
    const treeData = response.data.dictionaries || response.data
    dictionaryTreeData.value = treeData
    
    // 同时加载平铺的字典数据用于父级选择
    const flatResponse = await systemConfigApi.getSystemDictionaries(selectedDictType.value)
    const flatData = flatResponse.data.dictionaries || flatResponse.data
    flatDictionaries.value = flatData
  } catch (error: any) {
    console.error('加载字典数据失败:', error)
    
    if (detectExtensionConflict(error) || 
         error.code === 'NETWORK_ERROR' || 
         error.message?.includes('Network Error')) {
       
       if (retryCount < 2) {
         ElMessage.warning(`加载字典数据失败，正在重试... (${retryCount + 1}/3)`)
         setTimeout(() => loadDictionaries(retryCount + 1), 1000 * (retryCount + 1))
         return
       } else {
         const troubleshooting = showNetworkTroubleshooting()
         console.log(troubleshooting)
         ElMessage({
           message: '网络连接失败，请查看控制台获取详细的问题排查建议',
           type: 'error',
           duration: 8000,
           showClose: true
         })
       }
    } else {
      ElMessage.error(`加载字典数据失败: ${error.message || '未知错误'}`)
    }
  }
}

const renderDictNode = (h: any, { node, data }: any) => {
  const labelText = Array.isArray(data.dict_label) ? data.dict_label.join(', ') : (data.dict_label || '未命名')
  return h('div', { class: 'dict-node' }, [
    h('span', labelText),
    h('span', { class: 'dict-actions' }, [
      h(ElButton, {
        size: 'small',
        type: 'primary',
        onClick: () => editDictionary(data)
      }, () => '编辑'),
      h(ElButton, {
        size: 'small',
        type: 'danger',
        onClick: () => deleteDictionary(data)
      }, () => '删除')
    ])
  ])
}

const editDictionary = (dict: SystemDictionary) => {
  Object.assign(dictForm, dict)
  showCreateDictDialog.value = true
}

const deleteDictionary = async (dict: SystemDictionary) => {
  try {
    await ElMessageBox.confirm('确定要删除这个字典项吗？', '确认删除', {
      type: 'warning'
    })
    
    await systemConfigApi.deleteSystemDictionary(dict.id)
    ElMessage.success('删除成功')
    loadDictionaries()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const saveDictionary = async () => {
  try {
    if (dictForm.id) {
      await systemConfigApi.updateSystemDictionary(dictForm.id, dictForm)
      ElMessage.success('更新成功')
    } else {
      await systemConfigApi.createSystemDictionary(dictForm)
      ElMessage.success('创建成功')
    }
    
    showCreateDictDialog.value = false
    resetDictForm()
    loadDictionaries()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const resetDictForm = () => {
  Object.assign(dictForm, {
    dict_type: '',
    dict_key: '',
    dict_value: '',
    dict_label: '',
    sort_order: 0,
    parent_id: null,
    description: '',
    is_active: true
  })
}

// 生命周期
onMounted(() => {
  loadConfigs()
  loadDictTypes()
})
</script>

<style scoped>
.system-config {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.config-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.config-container {
  margin-top: 20px;
}

.config-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.config-categories {
  margin-top: 20px;
}

.category-section {
  margin-bottom: 30px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.category-header h3 {
  margin: 0;
  color: #409eff;
}

.inline-edit {
  width: 100%;
}

.config-value {
  word-break: break-all;
}

.json-value {
  font-family: monospace;
  font-size: 12px;
  color: #666;
}

.edit-actions,
.normal-actions {
  display: flex;
  gap: 5px;
}

.dictionary-container {
  margin-top: 20px;
}

.dictionary-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.dictionary-tree {
  margin-top: 20px;
}

.dict-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.dict-actions {
  display: flex;
  gap: 5px;
}

.batch-edit-container {
  margin-top: 10px;
}

.batch-edit-container h4 {
  margin-bottom: 15px;
  color: #409eff;
}
</style>